﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using cfg = System.Configuration;
using GoldPrinter;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win.UltraWinCalcManager;
using Infragistics.Win.CalcEngine;
using WeifenLuo.WinFormsUI.Docking;
namespace BYManageInfoSystem
{
    public partial class Frm_FinInvoiceRecordNew : DockContent
    {
        private DGBY.BLL.SJPackingTab m_bllSJPackingTab = new DGBY.BLL.SJPackingTab();
        private UltraGridCell m_activeCell = null;
        private bool m_bFilterTypeCheckedFlagLastTime = true;
        private int m_nCurCopyIndex = 0;
        private int m_nCopyNums = 0;
        private const Decimal m_dtFactor = 1.17M;
        private bool m_bSumStart = false;
        private int m_nSelectRowIndex = 0;
        private int m_nBatchExportMaxNum = 30;
        private List<string> lstContractTemp = new List<string>();
        private string m_strFolder = "d:/财务购货合同/";
        protected string templetFilePath = cfg.ConfigurationSettings.AppSettings["TempletFilePath"];
        private Dictionary<string, int> dicContractToBGCKHTTabID = new Dictionary<string, int>();
        static private DGBY.BLL.FactoryDataTab m_bllFactoryDataTab = new DGBY.BLL.FactoryDataTab();
        private DGBY.BLL.PaidanRegisterTab m_bllPaidanRegisterTab = new DGBY.BLL.PaidanRegisterTab();
        private readonly DGBY.BLL.BGCKHTTab m_bllBGCKHTTab = new DGBY.BLL.BGCKHTTab();
        private static  DGBY.BLL.FinInvoiceRecordTab_New m_bllFinInvoiceRecordTab_New = new DGBY.BLL.FinInvoiceRecordTab_New();
        private static DGBY.BLL.FinCheckInvoiceRecordDetailTab_New m_bllFinCheckInvoiceRecordDetailTab_New = new DGBY.BLL.FinCheckInvoiceRecordDetailTab_New();

        //static private DGBY.BLL.FactoryDataTab m_bllFactoryDataTab = new DGBY.BLL.FactoryDataTab();
        static private DGBY.BLL.FactoryGoodsTab m_bllFactoryGoodsTab = new DGBY.BLL.FactoryGoodsTab();
        private DGBY.BLL.DG_MonthRateReferenceTab m_billDG_MonthRateReferenceTab = new DGBY.BLL.DG_MonthRateReferenceTab();

        private int m_nDelIndex = -1;
        private bool m_bInsertFlag = false;
        private bool m_bCopyInsertFlag = false;
        private DGBY.Model.FinInvoiceRecordTab_New m_modelFinInvoiceRecordTab_New = null;

        DataSet m_dsAll = new DataSet();
        Dictionary<int, int> m_dicSelectID2RowNo = new Dictionary<int, int>();
        private bool m_bLastModifiedCellIsSelect = false;
     //   private Dictionary<string, Decimal> m_dicContract2ContractJine = new Dictionary<string, decimal>();
     //   private Dictionary<string, Decimal> m_dicContract2JiaShuiTotal = new Dictionary<string, decimal>();
      //  private int m_nSelectFinRecvMoneyDetailTab_NewID = 0;
      //  private int m_nCopyInsertIndex = -1;
        //public static void onAddCommerCheckFillBoxSheet(object sender, CommerCheckFillBoxEventArgs e)
        //{

        //    DataSet ds = m_bllFinInvoiceRecordTab_New.GetList("FinInvoiceRecordTab_New.PaidanRegisterTabID = '" + e.m_nPaidanID + "'");

        //    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        //    {
        //        return;
        //    }
        //    Decimal dtBackTaxPoint = 0;
        //    DataSet dsInfo = m_bllFactoryGoodsTab.GetGoodsBandInfo("PaidanRegisterTab.PaidanRegisterTabID = '"
        //        + e.m_nPaidanID.ToString() + "'");
        //    if (dsInfo.Tables.Count > 0 && dsInfo.Tables[0].Rows.Count > 0)
        //    {
        //        dtBackTaxPoint = Convert.ToDecimal(dsInfo.Tables[0].Rows[0]["退税点"].ToString());
        //    }
        //    int nFormulaSelector = 0;
        //    Decimal dtFactorA = 0;
        //    dsInfo = m_bllFactoryDataTab.GetFactorAInfo("PaidanRegisterTab.PaidanRegisterTabID = '"
        //        + e.m_nPaidanID.ToString() + "'");
        //    if (dsInfo.Tables.Count > 0 && dsInfo.Tables[0].Rows.Count > 0)
        //    {
        //        dtFactorA = Convert.ToDecimal(dsInfo.Tables[0].Rows[0]["系数A"].ToString());
        //        nFormulaSelector = Convert.ToInt32(dsInfo.Tables[0].Rows[0]["公式选择"].ToString(), 10);

        //    }

        //    DGBY.Model.FinInvoiceRecordTab_New modelFinInvoiceRecordTab_New = new DGBY.Model.FinInvoiceRecordTab_New();
        //    modelFinInvoiceRecordTab_New.PaidanRegisterTabID = e.m_nPaidanID;
        //    modelFinInvoiceRecordTab_New.KaiPiaoHuiLv = 0;
        //    modelFinInvoiceRecordTab_New.KaiPiaoDate = System.DateTime.Now.Date;
        //    modelFinInvoiceRecordTab_New.InvoiceNo = "";
        //    modelFinInvoiceRecordTab_New.JinE = 0;
        //    modelFinInvoiceRecordTab_New.ShuiJin = 0;
        //    modelFinInvoiceRecordTab_New.ChuKouYearMonth = "";
        //    modelFinInvoiceRecordTab_New.LuDanDate = System.DateTime.Now.Date;
        //    modelFinInvoiceRecordTab_New.BackTaxPoint = dtBackTaxPoint;
        //    modelFinInvoiceRecordTab_New.FactorA = dtFactorA;
        //    modelFinInvoiceRecordTab_New.FactorB = 1.17M;
        //    modelFinInvoiceRecordTab_New.PriceTaxFormulaSelector = nFormulaSelector;
        //    modelFinInvoiceRecordTab_New.JinECheckIgnore = 0;
        //    modelFinInvoiceRecordTab_New.IsGouHouContractPrint = "否";
        //    modelFinInvoiceRecordTab_New.IsKaiPiaoFinish = 0;

        //    m_bllFinInvoiceRecordTab_New.TransAdd(modelFinInvoiceRecordTab_New, e.m_SQLStringList, e.m_arrayList);
        //}
        public void InitUltraWinGridSetting()
        {
            this.ultraGrid1.DisplayLayout.Override.RowSelectors = Infragistics.Win.DefaultableBoolean.True;
            this.ultraGrid1.DisplayLayout.Override.RowSelectorNumberStyle = Infragistics.Win.UltraWinGrid.RowSelectorNumberStyle.VisibleIndex;
            this.ultraGrid1.DisplayLayout.Override.RowSelectorWidth = 35;
        }

        private void InitCombox()
        {
            DataTable dtNew = new DataTable();
            dtNew.Columns.Add("汇率种类", System.Type.GetType("System.String"));

            DataRow dr = dtNew.NewRow();
            dr["汇率种类"] = "美元开票汇率";
            dtNew.Rows.Add(dr.ItemArray);

            dr = dtNew.NewRow();
            dr["汇率种类"] = "港币开票汇率";
            dtNew.Rows.Add(dr.ItemArray);

            dr = dtNew.NewRow();
            dr["汇率种类"] = "售价汇率";
            dtNew.Rows.Add(dr.ItemArray);

            this.comboBoxHuilvCate.DataSource = dtNew;
            this.comboBoxHuilvCate.DisplayMember = "汇率种类";
            this.comboBoxHuilvCate.SelectedIndex = 0;
        }

        public Frm_FinInvoiceRecordNew()
        {
            InitializeComponent();
            InitUltraWinGridSetting();
            InitCombox();
            //Frm_CommerCheckFillBoxSheet.onAdd += onAddCommerCheckFillBoxSheet;
        }


        private void ShowAllRecord(string strWhere)
        {
            

            DataTable dtDispose = ultraGrid1.DataSource as DataTable;
            if (dtDispose != null
                && dtDispose.Rows.Count == m_dsAll.Tables[0].Rows.Count
                && this.checkBox1.Checked == m_bFilterTypeCheckedFlagLastTime)
            {
                foreach (Infragistics.Win.UltraWinGrid.UltraGridBand band in this.ultraGrid1.DisplayLayout.Bands)
                {
                    // since all rows in a band have the same filters in RowFilterMode.AllRowsInBand this
                    // will clear the filters
                    band.ColumnFilters.ClearAllFilters();
                    
                   
                }


                return;
                //dtDispose.Clear();
                //dtDispose.Dispose();
            }

            m_dsAll = m_bllFinInvoiceRecordTab_New.GetFinInvoiceRecordTabInfo(strWhere);
            ultraGrid1.DataSource = null;

            DataTable dtTemp = m_dsAll.Tables[0];
           
           

            ultraGrid1.DataSource = dtTemp;
            if (Frm_Main.m_bCompleteVer == false)
            {
                foreach (UltraGridColumn ugc in ultraGrid1.DisplayLayout.Bands[0].Columns)
                {
                    ugc.Hidden = true;
                }
                ultraGrid1.DisplayLayout.Bands[0].Columns["是否批量选中"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["是否已做完购货合同"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["客人"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["合同号"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["申报日期"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["币制"].Hidden = false;
            }
            else
            {
                ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;
            }
            //ultraGrid1.DisplayLayout.Bands[0].Columns["报关金额"].Hidden = false;
            //ultraGrid1.DisplayLayout.Bands[0].Columns["交财务退税资料单日期"].Hidden = false;
            //ultraGrid1.DisplayLayout.Bands[0].Columns["交财务退税资料单年月"].Hidden = false;
            
            //ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;
            //ultraGrid1.DisplayLayout.Bands[0].Columns[1].Hidden = true;
            //ultraGrid1.DisplayLayout.Bands[0].Columns[ds.Tables[0].Columns.Count - 1].Hidden = true;


        }
        private void ShowAllRecordReload(string strWhere)
        {
            
            DataSet ds = m_bllFinInvoiceRecordTab_New.GetFinInvoiceRecordTabInfo(strWhere);
            //ultraGrid1.DataSource = null;

            DataTable dtTemp = ds.Tables[0];

            dtTemp.Rows[0]["报关金额"] = 0;
            dtTemp.Rows[0]["合同金额"] = 0;
            dtTemp.Rows[0]["应退税额"] = 0;
            dtTemp.Rows[0]["本金"] = 0;
            dtTemp.Rows[0]["实际退税额"] = 0;

            DataTable dtOld = (DataTable)ultraGrid1.DataSource;
            object[] obj = new object[dtOld.Columns.Count];
            for (int i = 0; i < dtTemp.Rows.Count; i++)
            {
                dtTemp.Rows[i].ItemArray.CopyTo(obj, 0);
                dtOld.Rows.Add(obj);
            }

            ultraGrid1.DataSource = dtOld;
            ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;

            if (Frm_Main.m_bCompleteVer == false)
            {
                foreach (UltraGridColumn ugc in ultraGrid1.DisplayLayout.Bands[0].Columns)
                {
                    ugc.Hidden = true;
                }
                ultraGrid1.DisplayLayout.Bands[0].Columns["是否批量选中"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["是否已做完购货合同"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["客人"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["合同号"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["申报日期"].Hidden = false;
                ultraGrid1.DisplayLayout.Bands[0].Columns["币制"].Hidden = false;
            }


           // ultraGrid1.DisplayLayout.Bands[0].Columns[1].Hidden = true;
            //ultraGrid1.DisplayLayout.Bands[0].Columns[ds.Tables[0].Columns.Count - 1].Hidden = true;

            //  this.ultraGrid1.DisplayLayout.Bands[0].Columns["合同号"].ValueList = this.ultraDropDownPaidan;

        }
        private void buttonShowAll_Click(object sender, EventArgs e)
        {
            ShowAllRecord("");
        }
        public static void ultraGrid1_InitializeRowFilter(Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            //ultraGrid1.DisplayLayout.Override.RowSizing = RowSizing.AutoFree;
            //foreach (UltraGridColumn ugc in ultraGrid1.DisplayLayout.Bands[0].Columns)
            //    ugc.PerformAutoResize();
            // FILTER ROW FUNCTIONALITY RELATED ULTRAGRID SETTINGS
            //e.Layout.Override.RowFilterAction = RowFilterAction.DisableFilteredOutRows;
            // ----------------------------------------------------------------------------------
            // Enable the the filter row user interface by setting the FilterUIType to FilterRow.
            e.Layout.Override.FilterUIType = FilterUIType.FilterRow;
            e.Layout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            // FilterEvaluationTrigger specifies when UltraGrid applies the filter criteria typed 
            // into a filter row. Default is OnCellValueChange which will cause the UltraGrid to
            // re-filter the data as soon as the user modifies the value of a filter cell.
            e.Layout.Override.FilterEvaluationTrigger = FilterEvaluationTrigger.OnCellValueChange;
            //e.Layout.Override.RowFilterMode = RowFilterMode.AllRowsInBand;
            // By default the UltraGrid selects the type of the filter operand editor based on
            // the column's DataType. For DateTime and boolean columns it uses the column's editors.
            // For other column types it uses the Combo. You can explicitly specify the operand
            // editor style by setting the FilterOperandStyle on the override or the individual
            // columns.

            e.Layout.Override.FilterOperandStyle = FilterOperandStyle.DropDownList;

            // By default UltraGrid displays user interface for selecting the filter operator. 
            // You can set the FilterOperatorLocation to hide this user interface. This
            // property is available on column as well so it can be controlled on a per column
            // basis. Default is WithOperand. This property is exposed off the column as well.
            e.Layout.Override.FilterOperatorLocation = FilterOperatorLocation.WithOperand;

            // By default the UltraGrid uses StartsWith as the filter operator. You use
            // the FilterOperatorDefaultValue property to specify a different filter operator
            // to use. This is the default or the initial filter operator value of the cells
            // in filter row. If filter operator user interface is enabled (FilterOperatorLocation
            // is not set to None) then that ui will be initialized to the value of this
            // property. The user can then change the operator as he/she chooses via the operator
            // drop down.
            e.Layout.Override.FilterOperatorDefaultValue = FilterOperatorDefaultValue.StartsWith;

            // FilterOperatorDropDownItems property can be used to control the options provided
            // to the user for selecting the filter operator. By default UltraGrid bases 
            // what operator options to provide on the column's data type. This property is
            // avaibale on the column as well.
            //e.Layout.Override.FilterOperatorDropDownItems = FilterOperatorDropDownItems.All;

            // By default UltraGrid displays a clear button in each cell of the filter row
            // as well as in the row selector of the filter row. When the user clicks this
            // button the associated filter criteria is cleared. You can use the 
            // FilterClearButtonLocation property to control if and where the filter clear
            // buttons are displayed.
            e.Layout.Override.FilterClearButtonLocation = FilterClearButtonLocation.RowAndCell;

            // Appearance of the filter row can be controlled using the FilterRowAppearance proeprty.
            e.Layout.Override.FilterRowAppearance.BackColor = Color.LightYellow;

            // You can use the FilterRowPrompt to display a prompt in the filter row. By default
            // UltraGrid does not display any prompt in the filter row.
            e.Layout.Override.FilterRowPrompt = "Click here to filter data...";

            // You can use the FilterRowPromptAppearance to change the appearance of the prompt.
            // By default the prompt is transparent and uses the same fore color as the filter row.
            // You can make it non-transparent by setting the appearance' BackColorAlpha property 
            // or by setting the BackColor to a desired value.
            e.Layout.Override.FilterRowPromptAppearance.BackColorAlpha = Alpha.Opaque;

            // By default the prompt is spread across multiple cells if it's bigger than the
            // first cell. You can confine the prompt to a particular cell by setting the
            // SpecialRowPromptField property off the band to the key of a column.
            //e.Layout.Bands[0].SpecialRowPromptField = e.Layout.Bands[0].Columns[0].Key;

            // Display a separator between the filter row other rows. SpecialRowSeparator property 
            // can be used to display separators between various 'special' rows, including for the
            // filter row. This property is a flagged enum property so it can take multiple values.
            e.Layout.Override.SpecialRowSeparator = SpecialRowSeparator.FilterRow;

            // You can control the appearance of the separator using the SpecialRowSeparatorAppearance
            // property.
            e.Layout.Override.SpecialRowSeparatorAppearance.BackColor = Color.FromArgb(233, 242, 199);

            //   UltraGridBand band = e.Layout.Bands[0];
            //   band.ColumnFilters["原币金额"].FilterConditions.Clear();
            //   band.ColumnFilters["原币金额"].FilterConditions.Add(

            //FilterComparisionOperator.GreaterThan, 5);
            //   band.ColumnFilters["原币金额"].FilterConditions.Add(

            //FilterComparisionOperator.LessThan, 10);
            //   band.ColumnFilters["原币金额"].LogicalOperator = FilterLogicalOperator.And;
        }
        private void InitColumnWidth()
        {
            ultraGrid1.DisplayLayout.Bands[0].Columns["是否批量选中"].Width = 30;
            ultraGrid1.DisplayLayout.Bands[0].Columns["是否已做完购货合同"].Width = 50;
            ultraGrid1.DisplayLayout.Bands[0].Columns["客人"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["合同号"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["币制"].Width = 30;
            ultraGrid1.DisplayLayout.Bands[0].Columns["申报日期"].Width = 95;
            ultraGrid1.DisplayLayout.Bands[0].Columns["申报年月"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["报关金额"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["合同金额"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["本金"].Width = 80;
            ultraGrid1.DisplayLayout.Bands[0].Columns["应退税额"].Width = 80;
            ultraGrid1.DisplayLayout.Bands[0].Columns["实际退税额"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["开票日期"].Width = 95;
            ultraGrid1.DisplayLayout.Bands[0].Columns["发票号码"].Width = 90;
            ultraGrid1.DisplayLayout.Bands[0].Columns["金额"].Width = 80;
            ultraGrid1.DisplayLayout.Bands[0].Columns["税金"].Width = 80;
            ultraGrid1.DisplayLayout.Bands[0].Columns["价税合计"].Width = 80;
            ultraGrid1.DisplayLayout.Bands[0].Columns["出口年月"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["开票年月"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["录入发票日期"].Width = 95;
            ultraGrid1.DisplayLayout.Bands[0].Columns["美元开票汇率"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["港币开票汇率"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["售价汇率"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["系数A"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["系数B"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["退税点"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["经营公司"].Width = 120;
            ultraGrid1.DisplayLayout.Bands[0].Columns["部门"].Width = 75;
            ultraGrid1.DisplayLayout.Bands[0].Columns["价税合计公式选择"].Width = 60;
            ultraGrid1.DisplayLayout.Bands[0].Columns["金额核对忽略"].Width = 45;
            ultraGrid1.DisplayLayout.Bands[0].Columns["是否开票完成"].Width = 45;
            ultraGrid1.DisplayLayout.Bands[0].Columns["申报到开票天数"].Width = 45;
            ultraGrid1.DisplayLayout.Bands[0].Columns["开票到录入天数"].Width = 45;    
      
        }
        private void ultraGrid1_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            //this.ultraGrid1.DisplayLayout.UseFixedHeaders = true;
            //ultraGrid1.DisplayLayout.Bands[0].Columns["是否已做完购货合同"].Header.Fixed = true;
            //ultraGrid1.DisplayLayout.Bands[0].Columns["申报日期"].Header.Fixed = true;
            //ultraGrid1.DisplayLayout.Bands[0].Columns["报关单号"].Header.Fixed = true;
            //ultraGrid1.DisplayLayout.Bands[0].Columns["核销单号"].Header.Fixed = true;
            //ultraGrid1.DisplayLayout.Bands[0].Columns["统计日期"].Header.Fixed = true;
            //ultraGrid1.DisplayLayout.Bands[0].Columns["美元"].Header.Fixed = true;
            //ultraGrid1.DisplayLayout.Override.FixedHeaderIndicator = FixedHeaderIndicator.None;  // 不显示小图标
            
            SetSumColumn(e);
            e.Layout.Bands[0].Columns["开票日期"].Width = 120;
            e.Layout.Bands[0].Columns["开票日期"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DateWithoutDropDown;
           // e.Layout.Bands[0].Columns["发票号码"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.Edit;
            //this.ultraComboEditor1.au = Infragistics.Win.AutoSuggestFilterMode.StartsWith;

            

            if (this.checkBox1.Checked == true)
                ultraGrid1_InitializeRowFilter(e);
            else
                ClassUltraGridCommonSet.ultraGrid1_InitializeRowFilter(e);

            m_bFilterTypeCheckedFlagLastTime = this.checkBox1.Checked;

            ClassUltraGridCommonSet.LocalPrintPreveiw();

            foreach (UltraGridColumn column2 in ultraGrid1.DisplayLayout.Bands[0].Columns)
            {
                string str = column2.Header.Caption;
                if (str == "部门" || str == "客人" || str == "报关金额" || str == "币制"
                    || str == "合同金额" || str == "金额" || str == "税金" || str == "合同号"
                    || str == "出口年月" || str == "开票年月" || str == "经营公司"
                    || str == "是否已做完购货合同" || str == "录入发票日期"
                    || str == "应退税额" || str == "本金" || str == "实际退税额" || str == "申报日期")
                {
                    column2.CellAppearance.BackColor = Color.FromArgb(255,255,128);
                    column2.CellActivation = Activation.ActivateOnly;
                }
                
            }

            e.Layout.Bands[0].Columns["是否批量选中"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.CheckBox;

            e.Layout.Override.WrapHeaderText = Infragistics.Win.DefaultableBoolean.True;
            InitColumnWidth();
        }

        private void ultraGrid1_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter && e.Modifiers == Keys.Control)
            //{

            //    if (!m_bInsertFlag)
            //    {
            //        UltraGridRow row = this.ultraGrid1.DisplayLayout.Bands[0].AddNew();
            //        //  row.Cells[2] = DateTime.Parse("1900-01-01");
            //    }
            //}
            switch (e.KeyCode)
            {

                case Keys.Up:
                    {

                        int nColumnIndex = this.ultraGrid1.ActiveCell.Column.Index;
                        int nIndex = ultraGrid1.ActiveRow.Index;
                        if (nIndex > 0)
                            nIndex--;
                        this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                          false);
                        this.ultraGrid1.PerformAction(UltraGridAction.AboveCell, false,
                          false);
                        e.Handled = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].IgnoreRowColActivation = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activation = Activation.AllowEdit;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activate();
                        this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                          false);
                        break;
                    }

                case Keys.Down:
                    {
      
                        int nColumnIndex = this.ultraGrid1.ActiveCell.Column.Index;
                        int nIndex = ultraGrid1.ActiveRow.Index;
                        if (nIndex < ultraGrid1.Rows.Count - 1)
                            nIndex++;
                        this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                          false);
                        this.ultraGrid1.PerformAction(UltraGridAction.BelowCell, false,
                          false);
                        e.Handled = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].IgnoreRowColActivation = true;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activation = Activation.AllowEdit;
                        ultraGrid1.Rows[nIndex].Cells[nColumnIndex].Activate();
                        this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                          false);
                        break;
                    }

                case Keys.Right:
                    this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                      false);
                    this.ultraGrid1.PerformAction(UltraGridAction.NextCellByTab, false,
                      false);
                    e.Handled = true;
                    this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                      false);
                    break;
                case Keys.Left:
                    this.ultraGrid1.PerformAction(UltraGridAction.ExitEditMode, false,
                      false);
                    this.ultraGrid1.PerformAction(UltraGridAction.PrevCellByTab, false,
                      false);
                    e.Handled = true;
                    this.ultraGrid1.PerformAction(UltraGridAction.EnterEditMode, false,
                      false);
                    break;
            }
        }
           
        private void InitNewAddRowValue(int nIndex)
        {
            //UltraGridRow CurrentUGR = ultraGrid1.Rows[nIndex];

            //CurrentUGR.Cells["合同号"].Value = m_bllPaidanRegisterTab.GetMaxId() - 1;
            //CurrentUGR.Cells["开票日期"].Value = DateTime.Now.Date;
            //CurrentUGR.Cells["录入发票日期"].Value = DateTime.Now.Date;
            //CurrentUGR.Cells["发票号码"].Value = "";
            ////CurrentUGR.Cells["系数A公式"].Value = "";

            //CurrentUGR.Cells["金额"].Value = 0;
            //CurrentUGR.Cells["税金"].Value = 0;
            //CurrentUGR.Cells["美元开票汇率"].Value = 0;
            //CurrentUGR.Cells["港币开票汇率"].Value = 0;
            //CurrentUGR.Cells["售价汇率"].Value = 0;
            //CurrentUGR.Cells["退税点"].Value = 1.02;
            // CurrentUGR.Cells["系数A"].Value = 0.095;
            //CurrentUGR.Cells["系数B"].Value = 1.17;
            //CurrentUGR.Cells["价税合计公式选择"].Value = 0;
            //CurrentUGR.Cells["金额核对忽略"].Value = 0;

            //CurrentUGR.Cells["是否已做完购货合同"].Value = "否";

            //if (m_bInsertFlag)
            //{
            //    ultraGrid1.Rows[nIndex].Cells[2].Activation = Activation.ActivateOnly;
            //    m_bInsertFlag = false;
            //    AddGoodsDetail(nIndex);

            //}

        }
        private void InitNewAddRowValueCopyContract(int nIndex, int nNumIndex)
        {
            

            UltraGridRow CurrentUGR = ultraGrid1.Rows[nIndex];

            CurrentUGR.Cells["合同号"].Value = m_modelFinInvoiceRecordTab_New.PaidanRegisterTabID;
            CurrentUGR.Cells["开票日期"].Value = m_modelFinInvoiceRecordTab_New.KaiPiaoDate;
            CurrentUGR.Cells["录入发票日期"].Value = DateTime.Now.Date;
            string strInvoiceNo = (Convert.ToInt32(m_modelFinInvoiceRecordTab_New.InvoiceNo) + nNumIndex).ToString();
            CurrentUGR.Cells["发票号码"].Value = strInvoiceNo.PadLeft(m_modelFinInvoiceRecordTab_New.InvoiceNo.Length , '0');
            //CurrentUGR.Cells["系数A公式"].Value = "";
            CurrentUGR.Cells["金额"].Value = 0;
            CurrentUGR.Cells["税金"].Value = 0;
            CurrentUGR.Cells["美元开票汇率"].Value = m_modelFinInvoiceRecordTab_New.KaiPiaoHuiLv;
            CurrentUGR.Cells["港币开票汇率"].Value = m_modelFinInvoiceRecordTab_New.HKKaiPiaoHuiLv;
            CurrentUGR.Cells["售价汇率"].Value = m_modelFinInvoiceRecordTab_New.ShouJiaHuiLv;


            CurrentUGR.Cells["退税点"].Value = 1.02;
            CurrentUGR.Cells["系数A"].Value = 0.095;
            CurrentUGR.Cells["系数B"].Value = 1.17;
            CurrentUGR.Cells["价税合计公式选择"].Value = m_modelFinInvoiceRecordTab_New.PriceTaxFormulaSelector;
            CurrentUGR.Cells["金额核对忽略"].Value = 0;
            CurrentUGR.Cells["是否已做完购货合同"].Value = "是";
            if (m_bInsertFlag)
            {
                ultraGrid1.Rows[nIndex].Cells[2].Activation = Activation.ActivateOnly;
                m_bInsertFlag = false;
                AddGoodsDetail(nIndex);

            }

        }
        private void ultraGrid1_AfterRowInsert(object sender, RowEventArgs e)
        {
            ultraGrid1.Rows[e.Row.Index].Cells[1].IgnoreRowColActivation = true;
            ultraGrid1.Rows[e.Row.Index].Cells[1].Activation = Activation.AllowEdit;
            ultraGrid1.Rows[e.Row.Index].Cells[1].Activate();
            ultraGrid1.PerformAction(UltraGridAction.EnterEditMode);
            m_bInsertFlag = true;
            if (m_bCopyInsertFlag == false)
                InitNewAddRowValue(e.Row.Index);
            else
            {
            
                m_bCopyInsertFlag = false;
                InitNewAddRowValueCopyContract(e.Row.Index, m_nCurCopyIndex);

            }
        }

        private bool AddGoodsDetail(int nRowIndex)
        {

            try
            {
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[nRowIndex];
                
                DGBY.Model.FinInvoiceRecordTab_New modelFinInvoiceRecordTab_New = new DGBY.Model.FinInvoiceRecordTab_New();

                modelFinInvoiceRecordTab_New.PaidanRegisterTabID = Convert.ToInt32(CurrentUGR.Cells["合同号"].Value.ToString(), 10);
                DGBY.Model.PaidanRegisterTab pModel = m_bllPaidanRegisterTab.GetModel(modelFinInvoiceRecordTab_New.PaidanRegisterTabID);
                string strContractNo = pModel.ContractCode;
                DateTime dtTemp;
                if (CurrentUGR.Cells["开票日期"].Value.ToString() != "")
                {
                    dtTemp = (DateTime)CurrentUGR.Cells["开票日期"].Value;
                    modelFinInvoiceRecordTab_New.KaiPiaoDate = dtTemp.Date;
                }
                if (CurrentUGR.Cells["录入发票日期"].Value.ToString() != "")
                {
                    dtTemp = (DateTime)CurrentUGR.Cells["录入发票日期"].Value;
                    modelFinInvoiceRecordTab_New.LuDanDate = dtTemp.Date;
                }
      
                modelFinInvoiceRecordTab_New.InvoiceNo = CurrentUGR.Cells["发票号码"].Value.ToString();

                modelFinInvoiceRecordTab_New.JinE = Convert.ToDecimal(CurrentUGR.Cells["金额"].Value.ToString());
                modelFinInvoiceRecordTab_New.ShuiJin = Convert.ToDecimal(CurrentUGR.Cells["税金"].Value.ToString());
                modelFinInvoiceRecordTab_New.KaiPiaoHuiLv = Convert.ToDecimal(CurrentUGR.Cells["美元开票汇率"].Value.ToString());
                modelFinInvoiceRecordTab_New.HKKaiPiaoHuiLv = Convert.ToDecimal(CurrentUGR.Cells["港币开票汇率"].Value.ToString());
                modelFinInvoiceRecordTab_New.ShouJiaHuiLv = Convert.ToDecimal(CurrentUGR.Cells["售价汇率"].Value.ToString());

                
                modelFinInvoiceRecordTab_New.BackTaxPoint = Convert.ToDecimal(CurrentUGR.Cells["退税点"].Value.ToString());
                modelFinInvoiceRecordTab_New.FactorATransGongShi ="";

                modelFinInvoiceRecordTab_New.FactorA = Convert.ToDecimal(CurrentUGR.Cells["系数A"].Value.ToString());
                modelFinInvoiceRecordTab_New.FactorB = Convert.ToDecimal(CurrentUGR.Cells["系数B"].Value.ToString());
                modelFinInvoiceRecordTab_New.PriceTaxFormulaSelector = Convert.ToInt32(CurrentUGR.Cells["价税合计公式选择"].Value.ToString(), 10);
                modelFinInvoiceRecordTab_New.JinECheckIgnore = Convert.ToInt32(CurrentUGR.Cells["金额核对忽略"].Value.ToString(), 10);
                modelFinInvoiceRecordTab_New.IsGouHouContractPrint = CurrentUGR.Cells["是否已做完购货合同"].Value.ToString();

                int nRetID = m_bllFinInvoiceRecordTab_New.Add(modelFinInvoiceRecordTab_New);

                ShowAllRecordReload("FinInvoiceRecordTab_New.FinInvoiceRecordTab_NewID = '" + nRetID.ToString() + "'");
                //ShowAllRecordReload("");

                UpdateKaiPiaoFinishColumn(strContractNo);
                Frm_Main.Log2DB(this.Text, "复制增加", strContractNo);
                return true;

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void UpdateKaiPiaoFinishColumn(string strContractNo)
        {
            DataSet ds2
                    = m_bllFinInvoiceRecordTab_New.GetFinInvoiceRecordTabInfo("PaidanRegisterTab.ContractCode = '" + strContractNo + "'");
                
                if (ds2.Tables.Count > 0 && ds2.Tables[0].Rows.Count > 0)
                {
                    Decimal dtJiaShuiTotal = 0;
                    Decimal dtContractJinE = 0;
                    for (int i = 0; i < ds2.Tables[0].Rows.Count; i++)
                    {
                        int nID = (int)ds2.Tables[0].Rows[i]["FinInvoiceRecordTab_NewID"];
                        DGBY.Model.FinInvoiceRecordTab_New modelFIRTab_New = m_bllFinInvoiceRecordTab_New.GetModel(nID);
                        dtContractJinE = (Decimal)ds2.Tables[0].Rows[i]["合同金额"];
                        dtJiaShuiTotal += modelFIRTab_New.JinE;
                        dtJiaShuiTotal += modelFIRTab_New.ShuiJin;
                    }

                    //string strInvoiceNo = ds2.Tables[0].Rows[0]["发票号码"].ToString();
                    //int nIngore = Convert.ToInt32(ds2.Tables[0].Rows[0]["金额核对忽略"].ToString(), 10);

                    //if (strInvoiceNo == "" || nIngore == 1 || dtJiaShuiTotal == 0)
                    //    continue;

                    bool bIsKaiPiaoFinish = false;
                    if (dtContractJinE - dtJiaShuiTotal > 0.1M 
                        || dtJiaShuiTotal - dtContractJinE > 0.1M)
                    {
                        bIsKaiPiaoFinish = false;
                    }
                    else
                    {
                        bIsKaiPiaoFinish = true;
                    }

                    if (bIsKaiPiaoFinish)
                    {
                        for (int i = 0; i < ds2.Tables[0].Rows.Count; i++)
                        {
                            int nID = (int)ds2.Tables[0].Rows[i]["FinInvoiceRecordTab_NewID"];
                            DGBY.Model.FinInvoiceRecordTab_New modelFIRTab_New = m_bllFinInvoiceRecordTab_New.GetModel(nID);
                            modelFIRTab_New.IsKaiPiaoFinish = 1;
                            m_bllFinInvoiceRecordTab_New.Update(modelFIRTab_New);
                        }
                    }
                }
        }

        private bool ModifyGoodsDetail(int nRowIndex)
        {

            try
            {
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[nRowIndex];
                string strTemp = CurrentUGR.Cells[0].Value.ToString();
                if (strTemp == "")
                    return false;
                int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(CurrentUGR.Cells[0].Value.ToString(), 10);
                DGBY.Model.FinInvoiceRecordTab_New modelFinInvoiceRecordTab_New = m_bllFinInvoiceRecordTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);
                string strDanWei = CurrentUGR.Cells["合同号"].Value.ToString();

                //string strDanWei = CurrentUGR.Cells["单位"].Value.ToString();
                if (ClassInputValid.IsNum(strDanWei))
                {
                    modelFinInvoiceRecordTab_New.PaidanRegisterTabID = Convert.ToInt32(CurrentUGR.Cells["合同号"].Value.ToString(), 10);
                }
                else
                {
                    DataSet ds = m_bllPaidanRegisterTab.GetList("PaidanRegisterTab.ContractCode = '" + strDanWei + "'");
                    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        modelFinInvoiceRecordTab_New.PaidanRegisterTabID = Convert.ToInt32(ds.Tables[0].Rows[0]["PaidanRegisterTabID"].ToString(), 10);
                    }
                }

                //modelFinInvoiceRecordTab_New.PaidanRegisterTabID = Convert.ToInt32(CurrentUGR.Cells["合同号"].Value.ToString(), 10);
                if (CurrentUGR.Cells["开票日期"].Value.ToString() != "")
                {
                    DateTime dtTemp = (DateTime)CurrentUGR.Cells["开票日期"].Value;
                    modelFinInvoiceRecordTab_New.KaiPiaoDate = dtTemp.Date;
                }

                if (CurrentUGR.Cells["发票号码"].Value.ToString() == "" && this.textBoxNextInvoiceNo.Text == "")
                {
                    MessageBox.Show("请在下一个发票号码中或表格中录入发票号码！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }


                if (CurrentUGR.Cells["发票号码"].Value.ToString() == "" && this.textBoxNextInvoiceNo.Text != "")
                {
                    //modelFinInvoiceRecordTab_New.LuDanDate = System.DateTime.Now.Date;
                    modelFinInvoiceRecordTab_New.InvoiceNo = this.textBoxNextInvoiceNo.Text;
                }
                else if (CurrentUGR.Cells["发票号码"].Value.ToString() != "" 
                    && CurrentUGR.Cells["发票号码"].Value.ToString() != modelFinInvoiceRecordTab_New.InvoiceNo)
                {
                    modelFinInvoiceRecordTab_New.InvoiceNo = CurrentUGR.Cells["发票号码"].Value.ToString();
                }
                if (modelFinInvoiceRecordTab_New.InvoiceNo != "")
                {
                    modelFinInvoiceRecordTab_New.LuDanDate = System.DateTime.Now.Date;
                }
                string strInvoiceNo = (Convert.ToInt32(modelFinInvoiceRecordTab_New.InvoiceNo) + 1).ToString();
                this.textBoxNextInvoiceNo.Text = strInvoiceNo.PadLeft(modelFinInvoiceRecordTab_New.InvoiceNo.Length, '0');
                CurrentUGR.Cells["发票号码"].Value = modelFinInvoiceRecordTab_New.InvoiceNo;
                //if (modelFinInvoiceRecordTab_New.InvoiceNo == "" && CurrentUGR.Cells["发票号码"].Value.ToString() != "")
                //{
                //    modelFinInvoiceRecordTab_New.LuDanDate = System.DateTime.Now.Date;
                //}

                //modelFinInvoiceRecordTab_New.InvoiceNo = CurrentUGR.Cells["发票号码"].Value.ToString();

                decimal dDollarRate = Convert.ToDecimal(CurrentUGR.Cells["美元开票汇率"].Value.ToString());
                decimal dHKRate = Convert.ToDecimal(CurrentUGR.Cells["港币开票汇率"].Value.ToString());

                /***********************************************************************************************************/
                //判断开票汇率是否过大
                int nYearMonth = Convert.ToInt32(CurrentUGR.Cells["申报年月"].Value.ToString());
                if (nYearMonth >= 201208
                    && (modelFinInvoiceRecordTab_New.KaiPiaoHuiLv != dDollarRate || modelFinInvoiceRecordTab_New.HKKaiPiaoHuiLv != dHKRate))
                { 
                    
                    DGBY.Model.DG_MonthRateReferenceTab modelMonthRateReferenceTab = m_billDG_MonthRateReferenceTab.GetModelByYearMonth(nYearMonth);
                    if (null == modelMonthRateReferenceTab)
                    {
                        MessageBox.Show(nYearMonth.ToString() + "月汇率参考值未设置，请先设置后再进行修改！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }

                    if (modelFinInvoiceRecordTab_New.KaiPiaoHuiLv != dDollarRate)
                    {
                        decimal dDollarBalance = dDollarRate - modelMonthRateReferenceTab.DollarRate;
                        if (dDollarBalance > (decimal)0.04 || dDollarBalance < (decimal)-0.03)
                        {
                            if (MessageBox.Show("美元开票汇率" + dDollarRate.ToString() + "超出" + nYearMonth.ToString() + "月美元汇率参考值范围，确认修改？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK)
                                return false;
                        }
                    }

                    if (modelFinInvoiceRecordTab_New.HKKaiPiaoHuiLv != dHKRate)
                    {
                        decimal dHKBalance = dHKRate - modelMonthRateReferenceTab.HKRate;
                        if (dHKBalance > (decimal)0.007 || dHKBalance < (decimal)-0.003)
                        {
                            if (MessageBox.Show("港币开票汇率大于" + dHKRate.ToString() + "超出" + nYearMonth.ToString() + "月港币汇率参考值范围，确认修改？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK)
                                return false;
                        }
                    }
                }

                modelFinInvoiceRecordTab_New.KaiPiaoHuiLv = dDollarRate;
                modelFinInvoiceRecordTab_New.HKKaiPiaoHuiLv = dHKRate;
                /***********************************************************************************************************/

                modelFinInvoiceRecordTab_New.ShouJiaHuiLv = Convert.ToDecimal(CurrentUGR.Cells["售价汇率"].Value.ToString());

                modelFinInvoiceRecordTab_New.BackTaxPoint = Convert.ToDecimal(CurrentUGR.Cells["退税点"].Value.ToString());
                modelFinInvoiceRecordTab_New.FactorATransGongShi = "";
                modelFinInvoiceRecordTab_New.FactorA = Convert.ToDecimal(CurrentUGR.Cells["系数A"].Value.ToString());
                modelFinInvoiceRecordTab_New.FactorB = Convert.ToDecimal(CurrentUGR.Cells["系数B"].Value.ToString());

                modelFinInvoiceRecordTab_New.PriceTaxFormulaSelector = Convert.ToInt32(CurrentUGR.Cells["价税合计公式选择"].Value.ToString(), 10);
                modelFinInvoiceRecordTab_New.JinECheckIgnore = Convert.ToInt32(CurrentUGR.Cells["金额核对忽略"].Value.ToString(), 10);
                modelFinInvoiceRecordTab_New.IsGouHouContractPrint = CurrentUGR.Cells["是否已做完购货合同"].Value.ToString();
                
                modelFinInvoiceRecordTab_New.JinE = System.Math.Round(Convert.ToDecimal(CurrentUGR.Cells["价税合计"].Value.ToString()), 2) / m_dtFactor;
                modelFinInvoiceRecordTab_New.JinE = System.Math.Round(modelFinInvoiceRecordTab_New.JinE, 2);
                modelFinInvoiceRecordTab_New.ShuiJin = System.Math.Round(Convert.ToDecimal(CurrentUGR.Cells["价税合计"].Value.ToString()), 2) - modelFinInvoiceRecordTab_New.JinE;
              //  modelFinInvoiceRecordTab_New.ShuiJin = System.Math.Round(modelFinInvoiceRecordTab_New.ShuiJin, 2);


                m_bllFinInvoiceRecordTab_New.Update(modelFinInvoiceRecordTab_New);

                CurrentUGR.Cells["金额"].Value = modelFinInvoiceRecordTab_New.JinE;
                CurrentUGR.Cells["税金"].Value = modelFinInvoiceRecordTab_New.ShuiJin;
                CurrentUGR.Cells["录入发票日期"].Value = modelFinInvoiceRecordTab_New.LuDanDate;

                UpdateKaiPiaoFinishColumn(strDanWei);
                Frm_Main.Log2DB(this.Text, "修改", strDanWei);
                //ShowAllRecord("");
                // ShowAllRecord("BianHao = '" + modelFinRecvMoneyDetailTab_New.BianHao + "'");

                return true;

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void ultraGrid1_BeforeRowUpdate(object sender, CancelableRowEventArgs e)
        {
            try
            {
                UltraGridRow CurrentUGR;
                CurrentUGR = ultraGrid1.Rows[e.Row.Index];

                if (m_bInsertFlag)
                {
                    ultraGrid1.Rows[e.Row.Index].Cells[2].Activation = Activation.ActivateOnly;
                    m_bInsertFlag = false;
                    if (!AddGoodsDetail(e.Row.Index))
                        e.Cancel = true;



                }
                else//修改
                {
                    if(!m_bLastModifiedCellIsSelect)
                        ModifyGoodsDetail(e.Row.Index);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Cancel = true;
            }
        }

        private void ultraGrid1_BeforeRowsDeleted(object sender, BeforeRowsDeletedEventArgs e)
        {
            e.DisplayPromptMsg = false;
            if (!m_bInsertFlag)
            {
                int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(ultraGrid1.ActiveRow.Cells[0].Value.ToString(), 10);
                DGBY.Model.FinInvoiceRecordTab_New modelFinRecvMoneyDetailTab_NewOld = m_bllFinInvoiceRecordTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);

                if (modelFinRecvMoneyDetailTab_NewOld == null)
                {
                    MessageBox.Show("数据库不存在该记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (MessageBox.Show("确实要删除该条记录!", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                {
                    try
                    {

                        m_bllFinInvoiceRecordTab_New.Delete(nSelectFinRecvMoneyDetailTab_NewID);
                        Frm_Main.Log2DB(this.Text, "删除", ultraGrid1.ActiveRow.Cells["合同号"].Value.ToString());


                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        e.Cancel = true;
                    }
                }
                else
                {
                    e.Cancel = true;
                }
            }
            else
            {
                MessageBox.Show("插入未完成，不能删除记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Cancel = true;
            }
        }

        private void ultraGrid1_AfterCellActivate(object sender, EventArgs e)
        {
            int iIndex = this.ultraGrid1.ActiveCell.Row.Index;
            if (iIndex < 0)
                return;
            m_nDelIndex = ultraGrid1.ActiveRow.Index;
            m_activeCell = this.ultraGrid1.ActiveCell;
            if(m_activeCell.Column.Header.Caption.Contains("汇率"))
            //this.labelHuilv.Text = m_activeCell.Column.Header.Caption;
            //this.labelHuilv.ForeColor = Color.Red;
            if (m_bSumStart)
            {
                if (this.ultraGrid1.ActiveCell.Appearance.BackColor.Name == "0")
                {
                    this.ultraGrid1.ActiveCell.Appearance.BackColor = Color.Aqua;
                }
                else
                {
                    this.ultraGrid1.ActiveCell.Appearance.BackColor = Color.FromName("0");
                }
            }

        }

        private void ultraGrid1_AfterRowCancelUpdate(object sender, RowEventArgs e)
        {
            m_bInsertFlag = false;
        }

        private void ultraGrid1_BeforeCellCancelUpdate(object sender, CancelableCellEventArgs e)
        {
            m_bInsertFlag = false;
        }

        private void buttonExportToExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                }
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            this.ultraGridPrintDocument1.Grid = this.ultraGrid1;
            this.ultraPrintPreviewDialog1.Document = this.ultraGridPrintDocument1;
            this.ultraPrintPreviewDialog1.ShowDialog(this);
        }

        private void toolStripMenuItemAdd_Click(object sender, EventArgs e)
        {
            //if (!m_bInsertFlag)
            //{
            //    UltraGridRow row = this.ultraGrid1.DisplayLayout.Bands[0].AddNew();
            //    //  row.Cells[2] = DateTime.Parse("1900-01-01");
            //}
        }

        private void toolStripMenuItemDel_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确实要删除该记录么!", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.Cancel)
            {
                return;
            }
            int nIndex = m_nDelIndex;
            if (m_nDelIndex >= 0)
            {
                if (ultraGrid1.ActiveRow != null)
                {
                    ultraGrid1.ActiveRow.Delete(false);
                }
            }
            else
            {
                MessageBox.Show("请选中要删除的记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void buttonBatchModHuiLv_Click(object sender, EventArgs e)
        {
            if (m_activeCell == null)
            {
                MessageBox.Show("请选择要批量修改的列", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
            if (ugr.Length <= 0)
            {
                MessageBox.Show("没有要批量修改的行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            string strSql = @"update f set USDHuiLv = u.kaipiaohuilv,HKHuiLv = u.hkkaipiaohuilv
from FinCheckInvoiceRecordDetailTab_New f,FinInvoiceRecordTab_New u
where f.paidanregistertabid = u.paidanregistertabid
";
            if (this.comboBoxHuilvCate.Text == "美元开票汇率")
            {
                /************************************************************************/
                //检查美元汇率
                decimal dDollarRate = Convert.ToDecimal(this.textBoxKaiPiaoHuiLv.Text);
                foreach (int nID in m_dicSelectID2RowNo.Keys)
                {
                    DGBY.Model.FinInvoiceRecordTab_New modelFinInvoiceRecordTab_NewOld = m_bllFinInvoiceRecordTab_New.GetModel(nID);
                    UltraGridRow CurrentUGR = ultraGrid1.Rows[m_dicSelectID2RowNo[nID]];
                    int nYearMonth = Convert.ToInt32(CurrentUGR.Cells["申报年月"].Value.ToString());
                    if (nYearMonth >= 201208)
                    {
                        DGBY.Model.DG_MonthRateReferenceTab modelMonthRateReferenceTab = m_billDG_MonthRateReferenceTab.GetModelByYearMonth(nYearMonth);
                        if (null == modelMonthRateReferenceTab)
                        {
                            MessageBox.Show(nYearMonth.ToString() + "月汇率参考值未设置，请先设置后再进行修改！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        if (modelFinInvoiceRecordTab_NewOld.KaiPiaoHuiLv != dDollarRate)
                        {
                            decimal dDollarBalance = dDollarRate - modelMonthRateReferenceTab.DollarRate;
                            if (dDollarBalance > (decimal)0.04 || dDollarBalance < (decimal)-0.03)
                            {
                                if (MessageBox.Show("美元开票汇率" + dDollarRate.ToString() + "超出" + nYearMonth.ToString() + "月美元汇率参考值范围，确认修改？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK)
                                    return;
                            }
                        }
                    }
                }
                /************************************************************************/

                foreach (int nID in m_dicSelectID2RowNo.Keys)
                {
                    DGBY.Model.FinInvoiceRecordTab_New modelFinInvoiceRecordTab_NewOld = m_bllFinInvoiceRecordTab_New.GetModel(nID);
                    modelFinInvoiceRecordTab_NewOld.KaiPiaoHuiLv = Convert.ToDecimal(this.textBoxKaiPiaoHuiLv.Text);
                    m_bllFinInvoiceRecordTab_New.Update(modelFinInvoiceRecordTab_NewOld);

                    UltraGridRow CurrentUGR = ultraGrid1.Rows[m_dicSelectID2RowNo[nID]];

                    CurrentUGR.Cells["美元开票汇率"].Value = Convert.ToDecimal(this.textBoxKaiPiaoHuiLv.Text);
                }
                m_bllSJPackingTab.ExecuteSql(strSql);
            }
            else if (this.comboBoxHuilvCate.Text == "港币开票汇率")
            {
                /************************************************************************/
                //检查港币汇率
                decimal dHKRate = Convert.ToDecimal(this.textBoxKaiPiaoHuiLv.Text);
                foreach (int nID in m_dicSelectID2RowNo.Keys)
                {
                    DGBY.Model.FinInvoiceRecordTab_New modelFinInvoiceRecordTab_NewOld = m_bllFinInvoiceRecordTab_New.GetModel(nID);
                    UltraGridRow CurrentUGR = ultraGrid1.Rows[m_dicSelectID2RowNo[nID]];
                    int nYearMonth = Convert.ToInt32(CurrentUGR.Cells["申报年月"].Value.ToString());
                    if (nYearMonth >= 201208)
                    {
                        DGBY.Model.DG_MonthRateReferenceTab modelMonthRateReferenceTab = m_billDG_MonthRateReferenceTab.GetModelByYearMonth(nYearMonth);
                        if (null == modelMonthRateReferenceTab)
                        {
                            MessageBox.Show(nYearMonth.ToString() + "月汇率参考值未设置，请先设置后再进行修改！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        if (modelFinInvoiceRecordTab_NewOld.KaiPiaoHuiLv != dHKRate)
                        {
                            decimal dHKBalance = dHKRate - modelMonthRateReferenceTab.HKRate;
                            if (dHKBalance > (decimal)0.007 || dHKBalance < (decimal)-0.003)
                            {
                                if (MessageBox.Show("港币开票汇率" + dHKRate.ToString() + "超出" + nYearMonth.ToString() + "月港币汇率参考值范围，确认修改？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK)
                                    return;
                            }
                        }
                    }
                }
                /************************************************************************/

                foreach (int nID in m_dicSelectID2RowNo.Keys)
                {
                    DGBY.Model.FinInvoiceRecordTab_New modelFinInvoiceRecordTab_NewOld = m_bllFinInvoiceRecordTab_New.GetModel(nID);
                    modelFinInvoiceRecordTab_NewOld.HKKaiPiaoHuiLv = Convert.ToDecimal(this.textBoxKaiPiaoHuiLv.Text);
                    m_bllFinInvoiceRecordTab_New.Update(modelFinInvoiceRecordTab_NewOld);


                    UltraGridRow CurrentUGR = ultraGrid1.Rows[m_dicSelectID2RowNo[nID]];
                    CurrentUGR.Cells["港币开票汇率"].Value = Convert.ToDecimal(this.textBoxKaiPiaoHuiLv.Text);
                }
                m_bllSJPackingTab.ExecuteSql(strSql);
            }
            else if (this.comboBoxHuilvCate.Text == "售价汇率")
            {

                foreach (int nID in m_dicSelectID2RowNo.Keys)
                {
                    DGBY.Model.FinInvoiceRecordTab_New modelFinInvoiceRecordTab_NewOld = m_bllFinInvoiceRecordTab_New.GetModel(nID);
                    modelFinInvoiceRecordTab_NewOld.ShouJiaHuiLv = Convert.ToDecimal(this.textBoxKaiPiaoHuiLv.Text);
                    m_bllFinInvoiceRecordTab_New.Update(modelFinInvoiceRecordTab_NewOld);


                    UltraGridRow CurrentUGR = ultraGrid1.Rows[m_dicSelectID2RowNo[nID]];
                    CurrentUGR.Cells["售价汇率"].Value = Convert.ToDecimal(this.textBoxKaiPiaoHuiLv.Text);
                }
            }
            //if(this.checkBoxAutoClear.Checked == true)
            //    m_dicSelectID2RowNo.Clear();
            Frm_Main.Log2DB(this.Text, "批量修改", this.textBoxKaiPiaoHuiLv.Text);
            MessageBox.Show("批量修改开票汇率成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        private void ExportExcelSum(List<FinGouHuoContractSum> lstFinGouHuoContractSum)
        {
            if (Directory.Exists(m_strFolder))//判断是否存在
            {
                //if (File.Exists(strFolder + @"\" + strFin + ".jpg"))
                //    return;

            }
            else
            {
                //Response.Write("不存在，正在创建");
                Directory.CreateDirectory(m_strFolder);//创建新路径
            }

            string outFile = m_strFolder + "汇总表.xls";
            string templetFile = templetFilePath + "财务_购货合同汇总.xlt";
            //lstExcelFileName.Add(outFile);
           // lstFinGouHuoContractSum.Add(FinSum);
            ExcelBase eB = new ExcelBase(templetFile, outFile);

            try
            {
                eB.FinGouHuoSummaryToExcel(lstFinGouHuoContractSum, lstFinGouHuoContractSum.Count, 3, 1, "页", 0);
            }
            catch (System.Exception ex)
            {

            }

            eB.Close();
        }

        private void ExportExcel(int nPaiDanID, ArrayList lstExcelFileName
            , List<FinGouHuoContractSum> lstFinGouHuoContractSum, bool bClearRight)
        {
            //Dictionary<Decimal, Decimal> dicPax2JinE = new Dictionary<decimal, decimal>();
            FinGouHuoContractSum FinSum = new FinGouHuoContractSum();

            if (!Directory.Exists(m_strFolder))//判断是否存在
            {
                Directory.CreateDirectory(m_strFolder);//创建新路径
            }
            DataSet ds = m_bllBGCKHTTab.GetFinBuyGoodsContractList("PaidanRegisterTab.PaidanRegisterTabID = '" + nPaiDanID.ToString() + "'");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                FinSum.dtSBDate = (DateTime)ds.Tables[0].Rows[0]["申报日期"];
                FinSum.dtDeadlineDate = FinSum.dtSBDate.Date.AddDays(60);
                FinSum.dtHuiLv = (Decimal)ds.Tables[0].Rows[0]["美元开票汇率"];
                FinSum.dtHKHuiLv = (Decimal)ds.Tables[0].Rows[0]["港币开票汇率"];
                FinSum.nFormulaSelector = (int)ds.Tables[0].Rows[0]["价税合计公式选择"];
            }
            else
            {
                //   MessageBox.Show("该合同号对应的回收报关单未回来!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            string strFacName = "";
            string strBizhi = "";
            string strContractCode = "";
            DataSet dsTest = m_bllBGCKHTTab.GetGouHuoContractInfo("PaidanRegisterTab.PaidanRegisterTabID = '" + nPaiDanID.ToString() + "'");
            if (dsTest.Tables.Count > 0 && dsTest.Tables[0].Rows.Count > 0)
            {
                strFacName = dsTest.Tables[0].Rows[0]["工厂简称"].ToString();
                for (int i = 0; i < dsTest.Tables[0].Rows.Count; i++)
                {

                    Decimal dtBackTaxPoint = (Decimal)dsTest.Tables[0].Rows[i]["退税点"];
                    Decimal dtTemp = (Decimal)dsTest.Tables[0].Rows[i]["金额"];
                    //dicPax2JinE.Add(dtBackTaxPoint, dtTemp);

                    FinSum.strContractNo = dsTest.Tables[0].Rows[i]["合同号"].ToString();
                    strContractCode = FinSum.strContractNo;
                    FinSum.strBizhi = dsTest.Tables[0].Rows[i]["币制"].ToString();
                    strBizhi = FinSum.strBizhi;
                    FinSum.strGuiNo = dsTest.Tables[0].Rows[i]["集装箱柜号"].ToString();
                    FinSum.dtFactorA = (Decimal)dsTest.Tables[0].Rows[i]["系数A"] ;

                    FinGouHuoContractSum FGCSTemp = new FinGouHuoContractSum();
                    FGCSTemp = FinSum;
                    FGCSTemp.dtBackTaxPoint = dtBackTaxPoint;
                    FGCSTemp.dtBaoGuanJinE = dtTemp;
                    lstFinGouHuoContractSum.Add(FGCSTemp);
                }

                
            }

            
            DataSet ds2 = m_bllBGCKHTTab.GetFinBuyGoodsContractDetailList("PaidanRegisterTab.PaidanRegisterTabID = '" + nPaiDanID.ToString() + "'");

            DataTable dt = (DataTable)ds2.Tables[0];
            DataTable dt1 = (DataTable)ds.Tables[0];
      
            if (dt1 != null)
            {

            }
            else
            {
                return;
            }
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    
                    string outFile = m_strFolder + strContractCode + ".xls";
                    string templetFile = "";

                    if (Frm_Main.m_bCompleteVer == false)
                    {
                        if (bClearRight)
                        {
              
                            templetFile = templetFilePath + "财务_购货合同new.xlt";
                      
                        }
                    }
                    else
                    {
                        if (bClearRight)
                        {
                            if (strFacName == "浩成")
                            {
                                templetFile = templetFilePath + "财务_购货合同_浩成.xlt";
                            }
                            else
                            {
                                templetFile = templetFilePath + "财务_购货合同.xlt";
                            }
                        }
                        else
                            templetFile = templetFilePath + "财务_购货合同内部.xlt";
                    }

                    lstExcelFileName.Add(outFile);


                    //foreach (Decimal dtTax in dicPax2JinE.Keys)
                    //{
                    //    FinGouHuoContractSum FGCSTemp = new FinGouHuoContractSum();
                    //    FGCSTemp = FinSum;
                    //    FGCSTemp.dtBackTaxPoint = dtTax;
                    //    FGCSTemp.dtBaoGuanJinE = dicPax2JinE[dtTax];
                    //    lstFinGouHuoContractSum.Add(FGCSTemp);
                    //}

                   
                    ExcelBase eB = new ExcelBase(templetFile, outFile);

                    try
                    {
                        if (Frm_Main.m_bCompleteVer == false)
                        {
                            eB.FinBuyGoodsConstract_DataTableToExcel(dt, dt1, 16, 8, 1
                                , "页", 1, FinSum.strGuiNo, strBizhi, bClearRight);
                        }
                        else
                        {
                            eB.FinBuyGoodsConstract_DataTableToExcelComplete(dt, dt1, 16, 8, 1
                                , "页", 1, FinSum.strGuiNo, strBizhi, bClearRight);
                        }
                        
                    }
                    catch (System.Exception ex)
                    {

                    }

                    eB.Close();
                }
            }
            else
            {
                //  MessageBox.Show("购货合同明细不存在!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void buttonBatchExportContract_Click(object sender, EventArgs e)
        {

            Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
            if (ugr.Length <= 0)
            {
                MessageBox.Show("没有要批量修改的行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DateTime dt = System.DateTime.Now;
            string format = "yyyyMMddhhmmss";            // Use this format
            string strTempTime = dt.ToString(format);
            ExportExcel(true, strTempTime);
            //if(Frm_Main.m_bCompleteVer)
            //    ExportExcel(false, strTempTime);
            m_dicSelectID2RowNo.Clear();
        }

        private void ExportExcel(bool bIsClearRight, string strTempTime)
        {
            ArrayList lstExcelFileName = new ArrayList();
            List<FinGouHuoContractSum> lstFinGouHuoContractSum = new List<FinGouHuoContractSum>();

            List<int> lstPaidanRegisterTabID = new List<int>();
            foreach (int nID in m_dicSelectID2RowNo.Keys)
            {
                DGBY.Model.FinInvoiceRecordTab_New modelFinInvoiceRecordTab_NewOld = m_bllFinInvoiceRecordTab_New.GetModel(nID);
                modelFinInvoiceRecordTab_NewOld.IsGouHouContractPrint = "是";
                m_bllFinInvoiceRecordTab_New.Update(modelFinInvoiceRecordTab_NewOld);
                if (!lstPaidanRegisterTabID.Contains(modelFinInvoiceRecordTab_NewOld.PaidanRegisterTabID))
                {
                    lstPaidanRegisterTabID.Add(modelFinInvoiceRecordTab_NewOld.PaidanRegisterTabID);
                    //ExportExcel(modelFinInvoiceRecordTab_NewOld.PaidanRegisterTabID, lstExcelFileName);
                }

                UltraGridRow CurrentUGR = ultraGrid1.Rows[m_dicSelectID2RowNo[nID]];

                CurrentUGR.Cells["是否批量选中"].Value = 0;
            }

           

            if (lstPaidanRegisterTabID.Count() > m_nBatchExportMaxNum)
            {
                MessageBox.Show("批量导出合同的个数不能超过" + m_nBatchExportMaxNum.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (lstPaidanRegisterTabID.Count() < 1)
            {
                MessageBox.Show("没有选中任何需要导出的合同" + m_nBatchExportMaxNum.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            foreach (int nPaidanRegisterTabID in lstPaidanRegisterTabID)
            {
                ExportExcel(nPaidanRegisterTabID, lstExcelFileName, lstFinGouHuoContractSum, bIsClearRight);
            }
            if (Frm_Main.m_bCompleteVer)
            {
                ExportExcelSum(lstFinGouHuoContractSum);
                lstExcelFileName.Add(m_strFolder + "汇总表.xls");
            }


  
            ExcelBase eB = new ExcelBase();
            string outFile = "";
            if (Frm_Main.m_bCompleteVer)
            {
                if (bIsClearRight)
                    outFile = m_strFolder + strTempTime + ".xls";
                else
                    outFile = m_strFolder + strTempTime + "内部.xls";
            }
            else
            {
                //if(bIsClearRight)
                outFile = m_strFolder + strTempTime + ".xls";
                //else
                //    outFile = m_strFolder + strTempTime + "内部.xls";
            }
            eB.GouHuoBooks2Sheets(outFile, lstExcelFileName);
            eB.CloseAll();
        }

        private void SetSumColumn(Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            SummarySettings averageSummary =
e.Layout.Bands[0].Summaries.Add(
"报关金额",
SummaryType.Sum,
e.Layout.Bands[0].Columns["报关金额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

            averageSummary =
e.Layout.Bands[0].Summaries.Add(
"价税合计",
SummaryType.Sum,
e.Layout.Bands[0].Columns["价税合计"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

            averageSummary =
e.Layout.Bands[0].Summaries.Add(
"本金",
SummaryType.Sum,
e.Layout.Bands[0].Columns["本金"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

            averageSummary =
e.Layout.Bands[0].Summaries.Add(
"应退税额",
SummaryType.Sum,
e.Layout.Bands[0].Columns["应退税额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

            averageSummary =
e.Layout.Bands[0].Summaries.Add(
"实际退税额",
SummaryType.Sum,
e.Layout.Bands[0].Columns["实际退税额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;

            averageSummary =
e.Layout.Bands[0].Summaries.Add(
"合同金额",
SummaryType.Sum,
e.Layout.Bands[0].Columns["合同金额"]);
            averageSummary.SummaryPosition = SummaryPosition.UseSummaryPositionColumn;
            averageSummary.SummaryPositionColumn = averageSummary.SourceColumn;
            averageSummary.DisplayFormat = "{0:.##}";
            averageSummary.Band.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
            averageSummary.Band.Override.BorderStyleSummaryFooter = UIElementBorderStyle.None;
            averageSummary.SummaryDisplayArea = SummaryDisplayAreas.TopFixed;
        }
        CheckBoxOnHeader_CreationFilter aCheckBoxOnHeader_CreationFilter = new CheckBoxOnHeader_CreationFilter();

        private void Frm_FinInvoiceRecordNew_Load(object sender, EventArgs e)
        {
            this.ultraGrid1.CreationFilter = aCheckBoxOnHeader_CreationFilter;
            aCheckBoxOnHeader_CreationFilter.SetParam(m_dicSelectID2RowNo, this.ultraGrid1);

            this.buttonCheck.Visible = Frm_Main.m_bCompleteVer;
            this.buttonSumStart.Visible = Frm_Main.m_bCompleteVer;
            this.buttonSumStop.Visible = Frm_Main.m_bCompleteVer;
            this.buttonBatchModHuiLv.Visible = Frm_Main.m_bCompleteVer;
            this.buttonExportHuizong.Visible = Frm_Main.m_bCompleteVer;
            this.label1.Visible = Frm_Main.m_bCompleteVer;
            this.label2.Visible = Frm_Main.m_bCompleteVer;
            this.label3.Visible = Frm_Main.m_bCompleteVer;
            this.label4.Visible = Frm_Main.m_bCompleteVer;

            this.comboBoxHuilvCate.Visible = Frm_Main.m_bCompleteVer;
            this.textBoxKaiPiaoHuiLv.Visible = Frm_Main.m_bCompleteVer;
            this.textBoxTotal.Visible = Frm_Main.m_bCompleteVer;
            this.textBoxNextInvoiceNo.Visible = Frm_Main.m_bCompleteVer;

            this.toolStripMenuItemSetPayTaxPoint.Visible = Frm_Main.m_bCompleteVer; 
            
        }



       

        private void toolStripMenuItemSetPayTaxPoint_Click(object sender, EventArgs e)
        {
            try
            {

                UltraGridRow CurrentUGRFrom;
                CurrentUGRFrom = ultraGrid1.Rows[m_nDelIndex];
                int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(CurrentUGRFrom.Cells[0].Value.ToString(), 10);
                DGBY.Model.FinInvoiceRecordTab_New modelFinInvoiceRecordTab_New = m_bllFinInvoiceRecordTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);

                Frm_PayTaxPointSetting frm_PayTaxPointSetting = new Frm_PayTaxPointSetting(modelFinInvoiceRecordTab_New.PaidanRegisterTabID);
                frm_PayTaxPointSetting.StartPosition = FormStartPosition.CenterScreen;
                frm_PayTaxPointSetting.ShowDialog();

            }
            catch
            {
                MessageBox.Show("没有选择记录，无法复制！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        //private void CheckJinE()
        //{
        //    m_dicContract2JiaShuiTotal.Clear();
        //    m_dicContract2ContractJine.Clear();
        //    DataSet ds =
        //        m_bllFinInvoiceRecordTab_New.GetFinInvoiceRecordTabInfo("");
        //    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        //    {
        //        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        //        {
        //            string strContract = ds.Tables[0].Rows[i]["合同号"].ToString();
        //            Decimal dtContractJinE = Convert.ToDecimal(ds.Tables[0].Rows[i]["合同金额"].ToString());
        //            Decimal dtJiaShuiTotal = Convert.ToDecimal(ds.Tables[0].Rows[i]["价税合计"].ToString());

        //            string strInvoiceNo = ds.Tables[0].Rows[i]["发票号码"].ToString();
        //            int nIngore = Convert.ToInt32(ds.Tables[0].Rows[i]["金额核对忽略"].ToString(), 10);

        //            if (strInvoiceNo == "" || nIngore == 1 || dtJiaShuiTotal == 0)
        //            {
        //                ds.Tables[0].Rows.RemoveAt(i);
        //                i--;
        //                continue;
        //            }

        //            else if (dtContractJinE - dtJiaShuiTotal > 0.1M || dtJiaShuiTotal - dtContractJinE > 0.1M)
        //                continue;


        //            ds.Tables[0].Rows.RemoveAt(i);
        //            i--;
        //        }

        //        ultraGrid1.DataSource = null;


        //        ultraGrid1.DataSource = ds.Tables[0];
        //        ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;

        //    }
        //}

        private void CheckJinE()
        {

            DataSet ds =
                m_bllFinInvoiceRecordTab_New.GetFinInvoiceRecordTabInfo(
@"FinInvoiceRecordTab_New.JinECheckIgnore = 0 
and FinInvoiceRecordTab_New.IsKaiPiaoFinish = 0
and FinInvoiceRecordTab_New.InvoiceNo != ''");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                
                ultraGrid1.DataSource = null;


                ultraGrid1.DataSource = ds.Tables[0];
                ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;

            }
        }
        private void buttonCheck_Click(object sender, EventArgs e)
        {
            CheckJinE();
        }
        //private void buttonCheck_Click(object sender, EventArgs e)
        //{
        //    m_dicContract2JiaShuiTotal.Clear();
        //    m_dicContract2ContractJine.Clear();
        //    DataSet ds = 
        //        m_bllFinInvoiceRecordTab_New.GetFinInvoiceRecordTabInfo("");
        //    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        //    {
        //        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        //        {
        //            string strContract = ds.Tables[0].Rows[i]["合同号"].ToString();
        //            Decimal dtContractJinE = Convert.ToDecimal(ds.Tables[0].Rows[i]["合同金额"].ToString());
        //            Decimal dtJiaShuiTotal = Convert.ToDecimal(ds.Tables[0].Rows[i]["价税合计"].ToString());

        //            string strInvoiceNo = ds.Tables[0].Rows[i]["发票号码"].ToString();
        //            int nIngore = Convert.ToInt32(ds.Tables[0].Rows[i]["金额核对忽略"].ToString(), 10);

        //            if (strInvoiceNo == "" || nIngore == 1 || dtJiaShuiTotal == 0)
        //                continue;
          
        //            if (!m_dicContract2ContractJine.Keys.Contains(strContract))
        //                m_dicContract2ContractJine[strContract] = dtContractJinE;
        //            if (!m_dicContract2JiaShuiTotal.Keys.Contains(strContract))
        //                m_dicContract2JiaShuiTotal[strContract] = dtJiaShuiTotal;
        //            else
        //                m_dicContract2JiaShuiTotal[strContract] += dtJiaShuiTotal;
        //        }
                
        //    }

        //    string strNotify = "";
        //    int nCount = 0;
        //    foreach (string strTemp in m_dicContract2JiaShuiTotal.Keys)
        //    {
        //        nCount++;
        //        Decimal dtContractJinE = m_dicContract2ContractJine[strTemp];
        //        Decimal dtJiaShuiTotal = m_dicContract2JiaShuiTotal[strTemp];
        //        if (dtContractJinE - dtJiaShuiTotal > 0.1M || dtJiaShuiTotal - dtContractJinE > 0.1M)
        //        {
        //            if(nCount % 5 == 0)
        //                strNotify += strTemp + "\n";
        //            else
        //                strNotify += strTemp + ",\r\r\r";
        //        }
                    
        //    }
        //    if(strNotify != "")
        //        Frm_Main.Notify("金额检查", "以下合同号合同金额与价税合计之差大于0.1元\n" + strNotify, 600, 400, 10000);
        //    else
        //        Frm_Main.Notify("金额检查", "没有合同号合同金额与价税合计之差大于0.1元\n" + strNotify, 300, 200, 3000);

        //}
        //private void SetFormula(Control control, string formula)
        //{
        //    // To acces extender the CalcManager extender properties, call 
        //    // the first get the GetCalcSettings method.
        //    CalcSettings objCalcSettings = null;
        //    objCalcSettings = this.ultraCalcManager1.GetCalcSettings(control);

        //    // Set the formula. 
        //    objCalcSettings.Formula = formula;
        //}
      
        //private void textBoxHuiLvFormula_TextChanged(object sender, EventArgs e)
        //{
        //    SetFormula(this.textBoxHuiLvValue, this.textBoxHuiLvFormula.Text);
            
        //}

        //private void textBoxHuiLvValue_TextChanged(object sender, EventArgs e)
        //{
        //    UltraGridRow CurrentUGR = ultraGrid1.Rows[m_nSelectRowIndex];
        //    CurrentUGR.Cells["系数A"].Value = Convert.ToDecimal(this.textBoxHuiLvValue.Text);
        //    ModifyGoodsDetail(m_nSelectRowIndex);
        //}

        private void ultraGrid1_AfterCellUpdate(object sender, CellEventArgs e)
        {
            //if (e.Cell.Column.Key == "系数A公式")
            //{
            //    m_nSelectRowIndex = e.Cell.Row.Index;
            //    UltraGridRow CurrentUGR = ultraGrid1.Rows[m_nSelectRowIndex];
            //    this.textBoxHuiLvFormula.Text = e.Cell.Value.ToString();
            //}
        }

        //private void buttonBatchModFactorA_Click(object sender, EventArgs e)
        //{
        //    Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
        //    if (ugr.Length <= 0)
        //    {
        //        MessageBox.Show("没有要批量修改的行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //        return;
        //    }

        //    for (int i = 0; i < ugr.Length; i++)
        //    {
        //        int nID = Convert.ToInt32(ugr[i].Cells[0].Value.ToString(), 10);
        //        DGBY.Model.FinInvoiceRecordTab_New modelFinInvoiceRecordTab_NewOld = m_bllFinInvoiceRecordTab_New.GetModel(nID);
        //        modelFinInvoiceRecordTab_NewOld.FactorATransGongShi = this.textBoxFactorAFormula.Text;
        //        modelFinInvoiceRecordTab_NewOld.FactorA = this.ultraCalcManager1.Calculate(this.textBoxFactorAFormula.Text).ToDecimal();
        //        m_bllFinInvoiceRecordTab_New.Update(modelFinInvoiceRecordTab_NewOld);
        //    }


        //    MessageBox.Show("批量修改系数A公式成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //}

        private void ultraGrid1_MouseDown(object sender, MouseEventArgs e)
        {

           
            UltraGrid grid = (UltraGrid)sender;
            UIElement element = grid.DisplayLayout.UIElement.LastElementEntered;
            if (element == null)
                return;
            Infragistics.Win.UltraWinGrid.ColumnHeader columnHeader = element.GetContext(typeof(Infragistics.Win.UltraWinGrid.ColumnHeader)) as Infragistics.Win.UltraWinGrid.ColumnHeader;
            if (columnHeader != null)
            {
                string str = columnHeader.Caption;
                //if (str != "合同金额" && str != "报关金额" && str != "价税合计"
                //    && str != "应退税额" && str != "本金" && str != "实际退税额")
                if (str != "是否批量选中")
                    return;
                Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
                if (ugr.Length <= 0)
                {
                    return;
                }

                //for (int i = 0; i < ugr.Length; i++)
                //{
                //    int iIndex = ugr[i].Index;
                //    UltraGridRow CurrentUGR = ultraGrid1.Rows[iIndex];
                //    int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(CurrentUGR.Cells[0].Value.ToString(), 10);
                    
                //    m_dicSelectID2RowNo.Add(nSelectFinRecvMoneyDetailTab_NewID, iIndex);
                //}
          
            }
            else
            {
                // Set the grid's tooltip to null. 
                //  Debug.WriteLine("null");
            }  
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
            if (ugr.Length <= 0)
            {
                MessageBox.Show("没有要批量修改的行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            foreach (int nID in m_dicSelectID2RowNo.Keys)
            {
                DGBY.Model.FinInvoiceRecordTab_New modelFinInvoiceRecordTab_NewOld = m_bllFinInvoiceRecordTab_New.GetModel(nID);
                modelFinInvoiceRecordTab_NewOld.HKKaiPiaoHuiLv = Convert.ToDecimal(this.textBoxKaiPiaoHuiLv.Text);
                m_bllFinInvoiceRecordTab_New.Update(modelFinInvoiceRecordTab_NewOld);


                UltraGridRow CurrentUGR = ultraGrid1.Rows[m_dicSelectID2RowNo[nID]];
                //if (this.checkBoxAutoClear.Checked == true)
                //    CurrentUGR.Cells["是否批量选中"].Value = 0;
                CurrentUGR.Cells["港币开票汇率"].Value = Convert.ToDecimal(this.textBoxKaiPiaoHuiLv.Text); 
            }
            //if (this.checkBoxAutoClear.Checked == true)
            //    m_dicSelectID2RowNo.Clear();

            MessageBox.Show("批量修改开票汇率成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void 从合同集合中删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
            for (int i = 0; i < ugr.Length; i++)
            {
                if(ugr[i].Index == m_nDelIndex)
                    ugr[i].Appearance.BackColor = Color.Gray;

                //ugr[i].Cells[3].Appearance.BackColor
            }
            
        }

        private void buttonSumStart_Click(object sender, EventArgs e)
        {
            m_bSumStart = true;
            Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
            for (int i = 0; i < ugr.Length; i++)
            {
                for (int j = 0; j < ugr[i].Cells.Count; j++)
                {
                    if (ugr[i].Cells[j].Appearance.BackColor == Color.Aqua)
                    {
                        ugr[i].Cells[j].Appearance.BackColor = Color.FromName("0");
                    }
                }
            }
        }

        private void buttonSumStop_Click(object sender, EventArgs e)
        {
            try
            {
                Decimal dtTotal = 0;
                Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
                for (int i = 0; i < ugr.Length; i++)
                {
                    for (int j = 0; j < ugr[i].Cells.Count; j++)
                    {
                        if (ugr[i].Cells[j].Appearance.BackColor == Color.Aqua)
                        {
                            Decimal dtTemp = Convert.ToDecimal(ugr[i].Cells[j].Value.ToString());
                            dtTotal += dtTemp;
                            //ugr[i].Cells[j].Appearance.BackColor = Color.FromName("0");
                        }
                    }
                }

                this.textBoxTotal.Text = dtTotal.ToString();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }
        private void toolStripMenuItemCopyAdd_Click(object sender, EventArgs e)
        {
            m_nCurCopyIndex = 1;
            try
            {
                if (!m_bInsertFlag)
                {
                    UltraGridRow CurrentUGRFrom;
                    CurrentUGRFrom = ultraGrid1.Rows[m_nDelIndex];
                    if (CurrentUGRFrom.Cells["发票号码"].Value.ToString() == "")
                    {
                        MessageBox.Show("发票号码为空，不能复制增加", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    else
                    {
                        m_nCopyNums = 1;
                    }
                    int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(CurrentUGRFrom.Cells[0].Value.ToString(), 10);
                    m_modelFinInvoiceRecordTab_New = m_bllFinInvoiceRecordTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);


                    m_bCopyInsertFlag = true;
                    UltraGridRow row = this.ultraGrid1.DisplayLayout.Bands[0].AddNew();


                    //  row.Cells[2] = DateTime.Parse("1900-01-01");
                }
            }
            catch
            {
                MessageBox.Show("没有选择记录，无法复制！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }
        private void 复制增加多行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                m_nCurCopyIndex = 0;
                if (!m_bInsertFlag)
                {

                    UltraGridRow CurrentUGRFrom;
                    CurrentUGRFrom = ultraGrid1.Rows[m_nDelIndex];
                    if (CurrentUGRFrom.Cells["发票号码"].Value.ToString() == "")
                    {
                        MessageBox.Show("发票号码为空，不能复制增加", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    else
                    {
                        Frm_NewCopyRowsSet frm_NewCopyRowsSet = new Frm_NewCopyRowsSet();
                        frm_NewCopyRowsSet.StartPosition = FormStartPosition.CenterScreen;
                        frm_NewCopyRowsSet.ShowDialog();
                        m_nCopyNums = frm_NewCopyRowsSet.GetRows();
                        if (m_nCopyNums == 0)
                        {
                            MessageBox.Show("不能复制增加0行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                    }
                    int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(CurrentUGRFrom.Cells[0].Value.ToString(), 10);
                    m_modelFinInvoiceRecordTab_New = m_bllFinInvoiceRecordTab_New.GetModel(nSelectFinRecvMoneyDetailTab_NewID);

                    for (int i = 0; i < m_nCopyNums; i++)
                    {
                        m_nCurCopyIndex = i + 1;
                        m_bCopyInsertFlag = true;
                        UltraGridRow row = this.ultraGrid1.DisplayLayout.Bands[0].AddNew();
                    }


                    //  row.Cells[2] = DateTime.Parse("1900-01-01");
                }
            }
            catch
            {
                MessageBox.Show("没有选择记录，无法复制！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            
        }

        private void ultraGrid1_CellChange(object sender, CellEventArgs e)
        {
            if (!StringComparer.Ordinal.Equals(e.Cell.Column.Key, @"是否批量选中"))
            {
                m_bLastModifiedCellIsSelect = false;
                return;
            }
            m_bLastModifiedCellIsSelect = true;
            int iIndex = e.Cell.Row.Index;
            if (iIndex < 0)
                return;
            UltraGridRow CurrentUGR = ultraGrid1.Rows[iIndex];

           
            int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(CurrentUGR.Cells[0].Value.ToString(), 10);
         
            if (e.Cell.Text == "1")
            {
                m_dicSelectID2RowNo.Add(nSelectFinRecvMoneyDetailTab_NewID, iIndex);
            }
            else
            {
                m_dicSelectID2RowNo.Remove(nSelectFinRecvMoneyDetailTab_NewID);
            }
        }

        /*
 This CreationFilter class will create a CheckBoxUIElement in each Column Header
 whose DataType is boolean. It will fire the HeaderCheckBoxClicked event 
 whenever the CheckBox is clicked.
 Note that in order to maintain the CheckState, this CreationFilter uses the 
 Tag proprty of the Header. So if the program uses the tag for something else
 this will not work. 
*/
        // Implements the CreationFilter interface		
        public class CheckBoxOnHeader_CreationFilter : IUIElementCreationFilter
        {
            // This event will fire when the CheckBox is clicked. 
            public delegate void HeaderCheckBoxClickedHandler(object sender, HeaderCheckBoxEventArgs e);
            public event HeaderCheckBoxClickedHandler _CLICKED;
            public Dictionary<int, int> m_dicSelectID2RowNo = new Dictionary<int, int>();
            public Infragistics.Win.UltraWinGrid.UltraGrid m_ultraGrid1;
            public void SetParam(Dictionary<int, int> dicSelectID2RowNo, Infragistics.Win.UltraWinGrid.UltraGrid ultraGrid1)
            {
                m_dicSelectID2RowNo = dicSelectID2RowNo;
                m_ultraGrid1 = ultraGrid1;

            }
            public CheckBoxOnHeader_CreationFilter()
            {
                _CLICKED += new HeaderCheckBoxClickedHandler(aCheckBoxOnHeader_CreationFilter_HeaderCheckBoxClicked);
            }

            private void aCheckBoxOnHeader_CreationFilter_HeaderCheckBoxClicked(object sender, CheckBoxOnHeader_CreationFilter.HeaderCheckBoxEventArgs e)
            {
                // Check to see if the column is of type boolean.  If it is, set all the cells in that column to
                // whatever value the header checkbox is.
                if (e.Header.Column.Header.Caption == "是否批量选中")
                {
                    //foreach (UltraGridRow aRow in e.Rows)
                    //{
                    //    aRow.Cells[e.Header.Column.Index].Value = (e.CurrentCheckState == CheckState.Checked);
                    //}
                    if (e.CurrentCheckState == CheckState.Checked)
                    {
                        Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = m_ultraGrid1.Rows.GetFilteredInNonGroupByRows();
                        if (ugr.Length <= 0)
                        {
                            return;
                        }

                        for (int i = 0; i < ugr.Length; i++)
                        {
                            int iIndex = ugr[i].Index;
                            UltraGridRow CurrentUGR = m_ultraGrid1.Rows[iIndex];
                            int nSelectFinRecvMoneyDetailTab_NewID = Convert.ToInt32(CurrentUGR.Cells[0].Value.ToString(), 10);

                            CurrentUGR.Cells["是否批量选中"].Value = 1;
                            if (!m_dicSelectID2RowNo.Keys.Contains(nSelectFinRecvMoneyDetailTab_NewID))
                                m_dicSelectID2RowNo.Add(nSelectFinRecvMoneyDetailTab_NewID, iIndex);

                            //else
                            //{
                            //    CurrentUGR.Cells["是否批量选中"].Value = 0;
                            //    

                            //}
                        }
                    }
                    else
                    {
                        foreach (int nID in m_dicSelectID2RowNo.Keys)
                        {
                            UltraGridRow CurrentUGR = m_ultraGrid1.Rows[m_dicSelectID2RowNo[nID]];
                            CurrentUGR.Cells["是否批量选中"].Value = 0;
                        }

                        m_dicSelectID2RowNo.Clear();
                    }
                }
            }

            // EventArgs used for the HeaderCheckBoxClicked event. This event has to pass in the CheckState and the ColumnHeader
            #region HeaderCheckBoxEventArgs
            public class HeaderCheckBoxEventArgs : EventArgs
            {
                private Infragistics.Win.UltraWinGrid.ColumnHeader mvarColumnHeader;
                private CheckState mvarCheckState;
                private RowsCollection mvarRowsCollection;

                public HeaderCheckBoxEventArgs(Infragistics.Win.UltraWinGrid.ColumnHeader hdrColumnHeader, CheckState chkCheckState, RowsCollection Rows)
                {
                    mvarColumnHeader = hdrColumnHeader;
                    mvarCheckState = chkCheckState;
                    mvarRowsCollection = Rows;
                }

                // Expose the rows collection for the specific row island that the header belongs to
                public RowsCollection Rows
                {
                    get
                    {
                        return mvarRowsCollection;
                    }
                }

                public Infragistics.Win.UltraWinGrid.ColumnHeader Header
                {
                    get
                    {
                        return mvarColumnHeader;
                    }
                }

                public CheckState CurrentCheckState
                {
                    get
                    {
                        return mvarCheckState;
                    }
                    set
                    {
                        mvarCheckState = value;
                    }
                }
            }
            #endregion

            private void aCheckBoxUIElement_ElementClick(Object sender, Infragistics.Win.UIElementEventArgs e)
            {
                // Get the CheckBoxUIElement that was clicked
                CheckBoxUIElement aCheckBoxUIElement = (CheckBoxUIElement)e.Element;

                // Get the Header associated with this particular element
                Infragistics.Win.UltraWinGrid.ColumnHeader aColumnHeader = (Infragistics.Win.UltraWinGrid.ColumnHeader)aCheckBoxUIElement.GetAncestor(typeof(HeaderUIElement)).GetContext(typeof(Infragistics.Win.UltraWinGrid.ColumnHeader));

                // Set the Tag on the Header to the new CheckState
                aColumnHeader.Tag = aCheckBoxUIElement.CheckState;

                // So that we can apply various changes only to the relevant Rows collection that the header belongs to
                HeaderUIElement aHeaderUIElement = aCheckBoxUIElement.GetAncestor(typeof(HeaderUIElement)) as HeaderUIElement;
                RowsCollection hRows = aHeaderUIElement.GetContext(typeof(RowsCollection)) as RowsCollection;

                // Raise an event so the programmer can do something when the CheckState changes
                if (_CLICKED != null)
                    _CLICKED(this, new HeaderCheckBoxEventArgs(aColumnHeader, aCheckBoxUIElement.CheckState, hRows));
            }

            public bool BeforeCreateChildElements(Infragistics.Win.UIElement parent)  // Implements Infragistics.Win.IUIElementCreationFilter.BeforeCreateChildElements
            {
                // Don't need to do anything here
                return false;
            }

            public void AfterCreateChildElements(Infragistics.Win.UIElement parent) // Implements Infragistics.Win.IUIElementCreationFilter.AfterCreateChildElements
            {
                // Check for the HeaderUIElement
                if (parent is HeaderUIElement)
                {
                    // Get the HeaderBase object from the HeaderUIElement
                    Infragistics.Win.UltraWinGrid.HeaderBase aHeader = ((HeaderUIElement)parent).Header;

                    // Only put the checkbox into headers whose DataType is boolean
                    if (aHeader.Column.Header.Caption == "是否批量选中")
                    {
                        TextUIElement aTextUIElement;
                        CheckBoxUIElement aCheckBoxUIElement = (CheckBoxUIElement)parent.GetDescendant(typeof(CheckBoxUIElement));

                        // Since the grid sometimes re-uses UIElements, we need to check to make sure 
                        // the header does not already have a CheckBoxUIElement attached to it.
                        // If it does, we just get a reference to the existing CheckBoxUIElement,
                        // and reset its properties.
                        if (aCheckBoxUIElement == null)
                        {
                            //Create a New CheckBoxUIElement
                            aCheckBoxUIElement = new CheckBoxUIElement(parent);
                        }

                        // Get the TextUIElement - this is where the text for the 
                        // Header is displayed. We need this so we can push it to the right
                        // in order to make room for the CheckBox
                        aTextUIElement = (TextUIElement)parent.GetDescendant(typeof(TextUIElement));

                        // Sanity check
                        if (aTextUIElement == null)
                            return;

                        // Get the Header and see if the Tag has been set. If the Tag is 
                        // set, we will assume it's the stored CheckState. This has to be
                        // done in order to maintain the CheckState when the grid repaints and
                        // UIElement are destroyed and recreated. 
                        Infragistics.Win.UltraWinGrid.ColumnHeader aColumnHeader =
                            (Infragistics.Win.UltraWinGrid.ColumnHeader)aCheckBoxUIElement.GetAncestor(typeof(HeaderUIElement))
                            .GetContext(typeof(Infragistics.Win.UltraWinGrid.ColumnHeader));

                        if (aColumnHeader.Tag == null)
                            //If the tag was nothing, this is probably the first time this 
                            //Header is being displayed, so default to Indeterminate
                            aColumnHeader.Tag = CheckState.Indeterminate;
                        else
                            aCheckBoxUIElement.CheckState = (CheckState)aColumnHeader.Tag;

                        // Hook the ElementClick of the CheckBoxUIElement
                        aCheckBoxUIElement.ElementClick += new UIElementEventHandler(aCheckBoxUIElement_ElementClick);

                        // Add the CheckBoxUIElement to the HeaderUIElement
                        parent.ChildElements.Add(aCheckBoxUIElement);

                        // Position the CheckBoxUIElement. The number 3 here is used for 3
                        // pixels of padding between the CheckBox and the edge of the Header.
                        // The CheckBox is shifted down slightly so it is centered in the header.
                        aCheckBoxUIElement.Rect = new Rectangle(parent.Rect.X + 3, parent.Rect.Y + ((parent.Rect.Height - aCheckBoxUIElement.CheckSize.Height) / 2), aCheckBoxUIElement.CheckSize.Width, aCheckBoxUIElement.CheckSize.Height);

                        // Push the TextUIElement to the right a little to make 
                        // room for the CheckBox. 3 pixels of padding are used again. 
                        aTextUIElement.Rect = new Rectangle(aCheckBoxUIElement.Rect.Right + 3, aTextUIElement.Rect.Y, parent.Rect.Width - (aCheckBoxUIElement.Rect.Right - parent.Rect.X), aTextUIElement.Rect.Height);
                    }
                    else
                    {
                        // If the column is not a boolean column, we do not want to have a checkbox in it
                        // Since UIElements can be reused by the grid, there is a chance that one of the
                        // HeaderUIElements that we added a checkbox to for a boolean column header
                        // will be reused in a column that is not boolean.  In this case, we must remove
                        // the checkbox so that it will not appear in an inappropriate column header.
                        CheckBoxUIElement aCheckBoxUIElement = (CheckBoxUIElement)parent.GetDescendant(typeof(CheckBoxUIElement));

                        if (aCheckBoxUIElement != null)
                        {
                            parent.ChildElements.Remove(aCheckBoxUIElement);
                            aCheckBoxUIElement.Dispose();
                        }
                    }
                }
            }
        }

        private void buttonClearAllSelect_Click(object sender, EventArgs e)
        {
            foreach (int nID in m_dicSelectID2RowNo.Keys)
            {
                UltraGridRow CurrentUGR = ultraGrid1.Rows[m_dicSelectID2RowNo[nID]];
                CurrentUGR.Cells["是否批量选中"].Value = 0;
            }

            m_dicSelectID2RowNo.Clear();
        }

        private void ultraDropDownPaidan_TextChanged(object sender, EventArgs e)
        {

        }

        private void buttonExportHuizong_Click(object sender, EventArgs e)
        {
             Infragistics.Win.UltraWinGrid.UltraGridRow[] ugr = ultraGrid1.Rows.GetFilteredInNonGroupByRows();
            if (ugr.Length <= 0)
            {
                return;
            }
            string strSql = "";
            foreach (Infragistics.Win.UltraWinGrid.UltraGridBand band in this.ultraGrid1.DisplayLayout.Bands)
            {
                // since all rows in a band have the same filters in RowFilterMode.AllRowsInBand this
                // will clear the filters
                List<object> lstO = band.ColumnFilters.All.ToList();
                string strColumnName;
                string strColumnValue;
                foreach (object o in lstO)
                {
                    ColumnFilter cf = (ColumnFilter)o;
                    strColumnName = cf.Column.Key;
                    strColumnValue = cf.FilterConditions.Count > 0 ? ((FilterCondition)cf.FilterConditions.All[0]).CompareValue.ToString() : "";
                    if (strColumnName == "开票年月")
                    {
                        if (strColumnValue == "")
                            continue;
                

                        strSql = "CONVERT(varchar(6), KaiPiaoDate, 112) = '" + strColumnValue + "'";

                    }
                }
                if (strSql == "")
                {
                    MessageBox.Show("请选择开票年月！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                DataSet ds = m_bllFinInvoiceRecordTab_New.GetFinInvoiceRecordTabHuiZongInfo(strSql);
                DataTable dt = ds.Tables[0];
                ultraGrid2.DataSource = dt;
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.Filter = "Excel文件(*.xls)|*.xls";
                        string outFile = "";

                        if (sfd.ShowDialog() == DialogResult.OK)
                        {
                            outFile = sfd.FileName;
                        }
                        else
                        {
                            return;
                        }

                        ultraGridExcelExporter1.Export(ultraGrid2, outFile);
                    }
                }
            }
        }

        private void ultraGrid1_MouseClick(object sender, MouseEventArgs e)
        {
            //if (e.Button == MouseButtons.Left)
            //    contextMenuStrip1.Show(Cursor.Position);
        }
    }
}
